package com.phone.handle;

import com.phone.exception.ErrorCode;
import com.phone.exception.ErrorException;
import com.phone.exception.NoBindingIdException;
import org.hibernate.Session;


import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

/**
 * Created by tisen on 2017/9/5.
 */
public abstract class EntityHandle<T> implements HandleImp<T> {
    protected Session session;
    protected Class<T> entityClass;

    public EntityHandle() {
        Type genType = getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        entityClass = (Class) params[0];
    }

    public EntityHandle(Session session) {
        this();
        this.session = session;
    }

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    @Override
    public String add(T t) throws Exception {
        return session.save(t).toString();
    }

    @Override
    public void delete(String id) throws Exception {
        session.delete(get(id));
    }

    @Override
    public void update(T t) throws Exception {
        session.update(t);
    }

    @Override
    public void update(String id, T t) throws Exception {
        get(id);
        session.update(id, t);
    }

    @Override
    public List<T> search(String sql) throws Exception {
        return (List<T>) session.createQuery(sql).list();
    }

    @Override
    public T get(String id) throws Exception {
        T t = session.get(entityClass, id);
        if (t == null) {
            throw new ErrorException(ErrorCode.NOT_EXIST_ID);
        }
        return t;
    }

    @Override
    public boolean checkOwnerId(String ownerid) throws Exception {
        UserHandle userHandle = new UserHandle(session);
        try {
            userHandle.getById(ownerid);
        } catch (NoBindingIdException e) {
            throw new ErrorException(ErrorCode.NOT_EXIST_OWNER_ID);
        }
        return true;
    }
}
